package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.model.business.vo.ectemplate.EcTemplateFilterParam;
import com.ndp.fb.rdb.api.EcTemplateRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.EcTemplate;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateCategory;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateElementStyle;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateFont;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateGroupCnt;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.SQLUtil;
import com.ndp.fb.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by infi.he on 2016/4/18.
 */
@Service
public class EcTemplateRdbServiceImpl extends DaoTemplate implements EcTemplateRdbService {

    @Override
    public Long save(EcTemplate obj) {
        return saveResultId(obj);
    }

    @Override
    public void delLogic(Long id) {
        String sql1  = "delete from ec_template_category where 1=1 and template_id=?";
        getJdbcTemplate().update(sql1,new Object[]{id});

        String sql2  = "update ec_template set is_delete = 1 where 1=1 and id = ?";
        getJdbcTemplate().update(sql2,new Object[]{id});
    }

    @Override
    public EcTemplate updateStatus(Long id, int active) {
        String sql  = "update ec_template set active = ? where 1=1 and id = ? ";
        getJdbcTemplate().update(sql, new Object[]{active, id});
        return findById(id);
    }

    @Override
    public EcTemplate findByName(String name, Long orgId) {
        String sql = "select * from ec_template where template_name = ? and org_id = ?";
        return findOne(sql, new Object[]{name, orgId}, DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public void cover(Long id, String templateImg,  String templateContext) {
        String sql  = "update ec_template set template_img = ?, template_context = ? where 1=1 and id = ? ";
        getJdbcTemplate().update(sql, new Object[]{templateImg, templateContext, id});
    }


    public void updateDeleteStatus(Integer deleteStatus,Long id){
        String sql  = "update ec_template set is_delete = ? where  id = ? ";
        getJdbcTemplate().update(sql,new Object[]{deleteStatus,id});
    }

    @Override
    public void updateTemplateImg(Long id, String url) {
        String sql  = "update ec_template set template_img = ? where 1=1 and id = ? ";
        getJdbcTemplate().update(sql, new Object[]{url, id});
    }

    @Override
    public Pager<EcTemplate> getTemplateWithPager(Long orgId, String name, int order, List<Long> templateStatus, List<EcTemplateFilterParam> filterList, Integer firstResult, Integer sizeNo) {
        List paramValue = new ArrayList<>();
        if (StringUtil.isEmpty(name)) {
            name="";
        }
        StringBuffer sql = new StringBuffer("SELECT DISTINCT e.* FROM ec_template e,ec_materiel_category c ,");
        if(ListUtil.isNotEmpty(filterList)) {
            sql.append("(");
            for(int i=0; i<filterList.size();i++) {
                if(i>0)
                    sql.append(" UNION ALL \n");
                sql.append("SELECT template_id,category_id FROM ec_template_category WHERE category_id IN (" + SQLUtil.appendPlaceholder(filterList.get(i).getIds().size()) + ")");
                paramValue.addAll(filterList.get(i).getIds());
            }
            sql.append(")");
        } else {
            sql.append("ec_template_category");
        }
        sql.append(" t");
        sql.append(" WHERE e.id = t.template_id AND c.id= t.category_id AND e.org_id = ? AND e.is_delete = 0");
        paramValue.add(orgId);

        if(StringUtil.isNotEmpty(name)) {
            sql.append(" AND e.template_name LIKE ?");
            paramValue.add("%"+name+"%");
        }

        sql.append(" ORDER BY e.create_time");
        if(order != -1)
            sql.append(" desc");
        return findPager(sql.toString(), paramValue.toArray(), firstResult, sizeNo, DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public List<EcTemplate> findAllNewEcTemplate(Long orgId) {

        String sql = "SELECT DISTINCT\n" +
                "	e.*\n" +
                "FROM\n" +
                "	ec_template e,\n" +
                "	ec_materiel_category c,\n" +
                "	ec_template_category t\n" +
                "WHERE\n" +
                "	e.id = t.template_id\n" +
                "AND c.id = t.category_id\n" +
                "AND e.org_id = ? \n" +
                "AND e.is_delete = 0\n" +
                "ORDER BY\n" +
                "	e.create_time DESC";
        return getJdbcTemplate().query(sql, new Object[]{orgId}, DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public EcTemplate findById(Long templateId) {
        String sql = "select * from ec_template where id = ?";
        return findOne(sql, new Object[]{templateId}, DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public List<EcTemplate> findAll() {
        return findAll(DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public  List<EcTemplate> findByOrgId(Long orgId) {
        String sql = "select * from ec_template where is_delete = 0 and org_id = ?";
        return getJdbcTemplate().query(sql, new Object[]{orgId}, DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public void batchSaveTemplateCatalog(List<EcTemplateCategory> list) {
        for (EcTemplateCategory ecTemplateCategory : list) {
            Long templateId = ecTemplateCategory.getTemplateId();
            Long categoryId = ecTemplateCategory.getCategoryId();
            EcTemplateCategory ecTemplateCategory1 = findEcTemplateCategory(templateId, categoryId);
            if (ecTemplateCategory1 == null){
                List<EcTemplateCategory> temp = new ArrayList<>(1);
                temp.add(ecTemplateCategory);
                batchSaveResultId(temp);
            }
        }
    }

    public EcTemplateCategory findEcTemplateCategory(Long templateId,Long categoryId){
        String sql = "SELECT * from ec_template_category e where e.template_id = ? and e.category_id = ?";
        return findOne(sql,new Object[]{templateId,categoryId},DefaultRowMapper.autoRowMapper(EcTemplateCategory.class));
    }

    @Override
    public List<EcTemplate> findByOrgIdAndCategory(Long orgId, List<Long> ids) {
        String sql = "SELECT DISTINCT temp.*\n" +
                " from ec_template temp , ec_template_category cat \n" +
                "where temp.id = cat.template_id\n" +
                "and temp.is_delete = 0\n" +
                "and temp.active = 1\n" +
                "and temp.org_id = ?\n" +
                "and cat.category_id in ("+SQLUtil.appendPlaceholder(ids.size())+")";

        List<Object> values = new ArrayList<>();
        values.add(orgId);
        values.addAll(ids);
        return getJdbcTemplate().query(sql, values.toArray(),DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public void saveTemplateFont(EcTemplateFont ecTemplateFont) {
        saveResultId(ecTemplateFont);
    }

    @Override
    public void updateTmplBgStyle(Long templateId, String templateName, String designCode) {
        String sql  = "update ec_template set template_name = ?,template_bg_style = ? where 1=1 and id = ?";
        getJdbcTemplate().update(sql, new Object[]{templateName, designCode, templateId});
    }

    @Override
    public void updateTmplBk(Long templateId, String templateName, String designCode) {
        String sql  = "update ec_template set template_name = ?,template_bk = ? where 1=1 and id = ? ";
        getJdbcTemplate().update(sql, new Object[]{templateName, designCode, templateId});
    }

    @Override
    public List<EcTemplate> findAllEcTemplate() {
        String sql = "SELECT t.* FROM ec_template t  WHERE t.`is_delete` = 0";
        return getJdbcTemplate().query(sql,DefaultRowMapper.autoRowMapper(EcTemplate.class));
    }

    @Override
    public List<EcTemplateGroupCnt> getTemplateGroupCnt(List<Long> templateIds) {
        String sql = "SELECT b.template_id, COUNT(DISTINCT b.element_style_group_id) AS cnt FROM ec_template a, ec_template_element_style b WHERE a.id = b.template_id  and a.id IN (" + SQLUtil.appendPlaceholder(templateIds.size()) + ") GROUP BY a.id";
        return getJdbcTemplate().query(sql, templateIds.toArray(), DefaultRowMapper.autoRowMapper(EcTemplateGroupCnt.class));
    }
}
